﻿using AutoMapper;
using DictionaryWebApp.DTO;
using DictionaryWebApp.EF_Models;
using System;
using System.Diagnostics.Contracts;
using System.Linq;

namespace DictionaryWebApp.DAL
{
    public interface IDictionaryRepository
    {
        IndexWordViewModel[] GetWords(string userGuid);
        void AddWord(NewWordViewModel word, string userGuid);
        void DeleteWord(string wordGuid, string userId);
    }

    public class DictionaryRepository : RepositoryBase<NewWordViewModel, Word, DictionaryContext>, IDictionaryRepository
    {
        private DictionaryContext _dictionaryContext;

        public DictionaryRepository(DictionaryContext dictionaryContext)
            : base(dictionaryContext)
        {
            _dictionaryContext = dictionaryContext;
        }

        public IndexWordViewModel[] GetWords(string userGuid)
        {
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(userGuid));

            var dbWords = (from word in _dictionaryContext.Words
                           where word.UserID == userGuid
                           select word).ToArray();

            var dtoWords = Mapper.Map<Word[], IndexWordViewModel[]>(dbWords);

            return dtoWords;
        }

        public void AddWord(NewWordViewModel word, string userGuid)
        {
            Contract.Requires<ArgumentNullException>(word != null);
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(userGuid));

            word.UserID = userGuid;
            word.WordID = Guid.NewGuid().ToString();

            AddItem(word);
        }

        public void DeleteWord(string wordGuid, string userId)
        {
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(wordGuid));
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(userId));

            var wordItem = GetItem(wordGuid);

            if (wordItem.UserID != userId)
            {
                throw new Exception("User is not owner of word.");
            }

            DeleteItem(wordItem);
        }
    }
}